//
//  BVSearchDetailShopsViewController.m
//  BuyVegetables
//
//  Created by 叶思超 on 15/10/14.
//  Copyright (c) 2015年 叶思超. All rights reserved.
//

#import "BVSearchDetailShopsViewController.h"
#import "BVConst.h"
#import "UIView+Extension.h"
#import "HttpTool.h"
#import "BVSearchShopsCell.h"
#import "BVSearchShops.h"
#import "MJExtension.h"
#import "BVCorrectOrderViewController.h"
#import "BVLoginViewController.h"
#import "BVShopsLeftCategoryDetail.h"
#import "BVShopCart.h"
#import "BVShopCartCell.h"
#import "MBProgressHUD+MJ.h"
#import "MJRefresh.h"
#import "BVMyOrder.h"

@interface BVSearchDetailShopsViewController () <UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate, BVCorrectOrderViewControllerDelegate,BVSearchShopsCellDelegate>
/**
 *  搜索框
 */
@property (nonatomic, strong) UITextField *searchField;
/**
 *  创建tableview
 */
@property (nonatomic, strong) UITableView *tableView;
/**
 * 存储所有搜索到的商品
 */
@property (nonatomic, strong) NSMutableArray *shops;
/**
 *  商品总价格
 */
@property (nonatomic, strong) UILabel *priceLabel;
/**
 *  最低消费金额
 */
@property (nonatomic, copy) NSString *minMoney;
/**
 *  购物车
 */
@property (nonatomic, strong) UIButton *balanceButton;
/**
 *  左侧购物车按钮
 */
@property (nonatomic, strong) UIButton *shopCartButton;
/**
 *  购物车商品数量
 */
@property (nonatomic, strong) NSMutableArray *shopsCartCount;
/**
 *  购物车商品数量
 */
@property (nonatomic, strong) UIButton *shopCartFlag;
/**
 *  购物车tableView
 */
@property (nonatomic, strong) UITableView *shopCartTableView;
/**
 *  添加一个蒙板
 */
@property (nonatomic, strong) UIButton *coverButton;
// 当前页
@property (nonatomic, assign) NSInteger currentPage;

@end

@implementation BVSearchDetailShopsViewController{
    BVMyOrder *order;
}

- (UIButton *)coverButton {
    if (!_coverButton) {
        // 添加一个蒙板
        _coverButton = [[UIButton alloc] init];
        _coverButton.backgroundColor = [UIColor blackColor];
        _coverButton.alpha = 0.5;
        [_coverButton addTarget:self action:@selector(removeCoverClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _coverButton;
}

- (UITableView *)shopCartTableView {
    if (!_shopCartTableView) {
        _shopCartTableView  = [[UITableView alloc] init];
        _shopCartTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _shopCartTableView.delegate = self;
        _shopCartTableView.dataSource = self;
        [self.view addSubview:_shopCartTableView];
    }
    return _shopCartTableView;
}

- (UIButton *)shopCartFlag {
    if (!_shopCartFlag) {
        _shopCartFlag  = [[UIButton alloc] init];
        CGFloat shopCartFlagX = 15;
        CGFloat shopCartFlagy = -4;
        CGFloat shopCartFlagW = 15;
        CGFloat shopCartFlagH = 15;
        _shopCartFlag.frame = CGRectMake(shopCartFlagX, shopCartFlagy, shopCartFlagW, shopCartFlagH);
        _shopCartFlag.backgroundColor = BVBaseOrangeColor;
        _shopCartFlag.layer.cornerRadius  = shopCartFlagW * 0.5;
        _shopCartFlag.layer.masksToBounds = YES;
        [_shopCartFlag setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _shopCartFlag.titleLabel.font = [UIFont systemFontOfSize:10];
        [self.shopCartButton addSubview:_shopCartFlag];
    }
    return _shopCartFlag;
}

- (NSMutableArray *)shopsCartCount {
    if (!_shopsCartCount) {
        _shopsCartCount = [NSMutableArray array];
    }
    return _shopsCartCount;
}

- (NSMutableArray *)shops {
    if (!_shops) {
        _shops = [NSMutableArray array];
    }
    return _shops;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.frame = CGRectMake(-12, 64, BVScreenW + 24, BVScreenH - 64 - 40);
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle  = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = 150;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (NSMutableArray *)orders
{
    if (!_orders) {
        _orders = [NSMutableArray array];
    }
    return _orders;
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self loadMyOrderData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.currentPage = 1;
    // 设置导航栏
    [self setupNav];
    
    if  (self.titleStr){
         [self loadSearchData];
    }
    // 加载数据
    // 获取消费最低金额
    [self setupMinMoney];
    
    [self.tableView addHeaderWithTarget:self action:@selector(loadSearchData)];
    [self.tableView addFooterWithTarget:self action:@selector(loadMoreData)];
}

#pragma mark -- 获取我的订单
//获取我的订单
- (void)loadMyOrderData{
    //拼接路径
    NSString *url = [NSString stringWithFormat:@"%@/VegetablePayAPI/getMyOrderListById",Path];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *userinfo = [defaults objectForKey:@"USERINFO"];
    NSString *user_id = userinfo[@"id"];
    
    if (user_id != nil) {
        params[@"user_id"] = user_id;
        [HttpTool get:url params:params success:^(id responseObj) {
            if ([responseObj[@"code"] isEqualToString:@"1"]) {
                NSArray *array = [BVMyOrder objectArrayWithKeyValuesArray:responseObj[@"data"]];
                [self.orders addObjectsFromArray:array];
                order = self.orders[0];
                [self setupBaseInfo];
                
                //                [self.tableView reloadData];
            } else {
                order = nil;
                [self setupBaseInfo];
                
            }
        } failure:^(NSError *error) {
        }];
    }else{
        order = nil;
        [self setupBaseInfo];
    }
}

#pragma mark -- 获取商品最低金额
- (void)setupMinMoney {
    // 拼接路径
    NSString *url = [NSString stringWithFormat:@"%@/VegetableUserAPI/getMinMoneyInfo", Path];
    
    [HttpTool get:url params:nil success:^(id responseObj) {
        if ([responseObj[@"code"] isEqualToString:@"1"]) {
            BVLog(@"请求成功=====%@", responseObj);
            self.minMoney = responseObj[@"data"][@"money"];
            /**
             *  底部购物车
             */
           [self setupBottomShopCart];
            
        } else {
            
        }
    } failure:^(NSError *error) {
        BVLog(@"请求失败%@", error);
    }];
}

#pragma mark -- 加载搜索到的数据
- (void)loadSearchData {
    // 拼接路径
    NSString *url = [NSString stringWithFormat:@"%@/VegetableUserAPI/getSearchVegetableListByName", Path];
    
    // 请求参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    //判断传到服务器的请求参数是否含有[省]和[市]
        params[@"province"] = [[defaults objectForKey:@"provice"] substringToIndex:2];
        params[@"city"] = [[defaults objectForKey:@"city"] substringToIndex:2];
    
    if ([defaults objectForKey:@"dist"]) {
        params[@"dist"] = [defaults objectForKey:@"dist"];
       NSLog(@"%@",params[@"dist"]);
    }

    params[@"title"] = self.titleStr;
    params[@"page"] = @(1);
    
    [HttpTool get:url params:params success:^(id responseObj) {
        
        NSLog(@"------%@",responseObj);
        
        if ([responseObj[@"code"] isEqualToString:@"1"]) {
            [self.shops removeAllObjects];

            NSArray *array = [BVShopsLeftCategoryDetail objectArrayWithKeyValuesArray:responseObj[@"data"]];
            
            [self.shops addObjectsFromArray:array];
            
            // 刷新tableview
            [self.tableView reloadData];
            
            [self.tableView headerEndRefreshing];
        } else {
            [MBProgressHUD showError:@"没有搜索到该商品" toView:self.view];
            [self.tableView headerEndRefreshing];
        }
    } failure:^(NSError *error) {
        [self.tableView headerEndRefreshing];
    }];
}

- (void)loadMoreData {
    self.currentPage++;
    
    // 拼接路径
    NSString *url = [NSString stringWithFormat:@"%@/VegetableUserAPI/getSearchVegetableListByName", Path];

    // 请求参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    params[@"province"] = [defaults objectForKey:@"provice"];
    params[@"city"] = [defaults objectForKey:@"city"];
    if ([defaults objectForKey:@"dist"]) {
        params[@"dist"] = [defaults objectForKey:@"dist"];
    }
    
    params[@"title"] = self.titleStr;
    params[@"page"] = [NSString stringWithFormat:@"%ld", (long)self.currentPage];
    
    [HttpTool get:url params:params success:^(id responseObj) {
        if ([responseObj[@"code"] isEqualToString:@"1"]) {
            
            NSArray *array = [BVShopsLeftCategoryDetail objectArrayWithKeyValuesArray:responseObj[@"data"]];
            
            [self.shops addObjectsFromArray:array];
            
            // 刷新tableview
            [self.tableView reloadData];
            
            [self.tableView footerEndRefreshing];
        } else {

            [MBProgressHUD showSuccess:@"没有更多了!" toView:self.view];
            self.tableView.footerHidden = YES;
        }
    } failure:^(NSError *error) {
        BVLog(@"请求失败-------%@", error);
        [self.tableView footerEndRefreshing];
    }];
}
#pragma mark BVSearchShopsCellDelegate
- (void)bvSearchShopsCell:(BVSearchShopsCell *)cell shopsCountChanged:(NSString *)countStr{
    
    NSIndexPath * indexPath = [self.tableView indexPathForCell:cell];
    BVShopsLeftCategoryDetail *detailShops = self.shops[indexPath.row];
        if ([BVShopCart lookUpShop:detailShops] != nil) { // 商品已在购物车
            // 修改商品
            [BVShopCart modifyShopToCartL:detailShops count:countStr.integerValue];
        } else { // 新商品
            // 添加商品到数据库
            [BVShopCart addShopToCart:detailShops];
            [BVShopCart modifyShopToCartL:detailShops count:countStr.integerValue];
        }
        
        // 显示购物车标识
        self.shopCartFlag.hidden = NO;
        
        // 设置购物车基本信息
        [self setupBaseInfo];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:ChangeShopCluntNotification object:nil userInfo:nil];
}

#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.tableView == tableView) {
        if (self.shops.count == 0) {
            return 0;
        }
        return self.shops.count;
    } else {
        if (self.shopsCartCount.count == 0) {
            return 0;
        }
        return self.shopsCartCount.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.tableView == tableView) {
        // 创建cell
        BVSearchShopsCell *cell = [BVSearchShopsCell cell];

        // 增加商品按钮
        cell.addButton.tag = indexPath.row + 200;
        [cell.addButton addTarget:self action:@selector(addShops:) forControlEvents:UIControlEventTouchUpInside];

        // 减少商品
        cell.subButton.tag = indexPath.row + 500;
        [cell.subButton addTarget:self action:@selector(subShops:) forControlEvents:UIControlEventTouchUpInside];

        // 传递数据模型
        cell.searchShops = self.shops[indexPath.row];

        //设置代理
        cell.delegate = self;

        return cell;
    } else {
        // 创建cell
        BVShopCartCell *cell = [BVShopCartCell cell];

        // 增加商品
        cell.addBtn.tag = 300 + indexPath.row;
        [cell.addBtn addTarget:self action:@selector(addBtnClick:) forControlEvents:UIControlEventTouchUpInside];

        // 减少商品数量
        cell.subBtn.tag = 600 + indexPath.row;
        [cell.subBtn addTarget:self action:@selector(subBtnClick:) forControlEvents:UIControlEventTouchUpInside];

        // 传递数据模型
        cell.shopsDetail = self.shopsCartCount[indexPath.row];

        return cell;
    }
}

#pragma mark -- 购物车
- (void)setupBottomShopCart {
    // 购物车父视图
    UIView *leftShopCart = [[UIView alloc] init];
    leftShopCart.frame = CGRectMake(0, BVScreenH - 40,  BVScreenW, 40);
    leftShopCart.backgroundColor = [UIColor whiteColor];
    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(0, 0, BVScreenW, 0.5);
    label.backgroundColor = BVBackgroundLightGrayColor;
    [leftShopCart addSubview:label];
    [self.view addSubview:leftShopCart];

    // 左侧购物车按钮
    UIButton *shopCartButton = [[UIButton alloc] init];
    shopCartButton.frame = CGRectMake(10, 8, 24, 24);
    shopCartButton.backgroundColor = [UIColor whiteColor];
    shopCartButton.enabled = NO;
    [shopCartButton setImage:[UIImage imageNamed:@"gwc"] forState:UIControlStateNormal];
    [shopCartButton addTarget:self action:@selector(shopCartButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [leftShopCart addSubview:shopCartButton];
    self.shopCartButton = shopCartButton;

    // 总价格
    self.priceLabel = [[UILabel alloc] init];
    self.priceLabel.textColor = BVBaseOrangeColor;
    self.priceLabel.frame = CGRectMake(CGRectGetMaxX(shopCartButton.frame) + 20, 8, BVScreenW * 0.7 - CGRectGetMaxX(shopCartButton.frame) - 10, shopCartButton.height);
    self.priceLabel.text = @"¥0";
    self.priceLabel.font = [UIFont systemFontOfSize:15];
    [leftShopCart addSubview:self.priceLabel];

    // 右侧结算按钮
    UIButton *balanceButton = [[UIButton alloc] init];
    balanceButton.frame = CGRectMake(BVScreenW * 0.7, 0, BVScreenW * 0.3, leftShopCart.height);
    balanceButton.enabled = NO;
    [balanceButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [balanceButton setTitle:[NSString stringWithFormat:@"还差%@元", self.minMoney] forState:UIControlStateNormal];
    balanceButton.titleLabel.font = [UIFont systemFontOfSize:15];
    balanceButton.backgroundColor = BVColor(153, 153, 153);
    [balanceButton addTarget:self action:@selector(correctOrderClick) forControlEvents:UIControlEventTouchUpInside];
    [leftShopCart addSubview:balanceButton];
    self.balanceButton = balanceButton;

    // 设置购物车基本信息
    [self setupBaseInfo];
}

#pragma  mark -- 设置购物车基本信息
- (void)setupBaseInfo {
    // 清空数组
    [self.shopsCartCount removeAllObjects];
    
    NSString *nowDate = [self getCurrentTime];
    NSString *orderDate = [order.order_time substringToIndex:10];
    
    // 商品数量
    [self.shopsCartCount addObjectsFromArray:[BVShopCart shopsCount:1]];
    
    if (self.shopsCartCount.count != 0) {
        self.shopCartFlag.hidden = NO;
        CGFloat allPrice   = 0.0;
        NSInteger allShops = 0;
        for (NSInteger i = 0; i < self.shopsCartCount.count; i++) {
            BVShopsLeftCategoryDetail *detail = self.shopsCartCount[i];
            
            allPrice += [BVShopCart shopCartCounts:detail] * [detail.each_bag_money floatValue];
            
            if ([nowDate isEqualToString:orderDate] && allPrice > 0.0) {
                
                [self.balanceButton setTitle:@"去结算" forState:UIControlStateNormal];
                self.balanceButton.backgroundColor = BVBaseOrangeColor;
                
                self.balanceButton.enabled = YES;
                
            } else {
                
                if ([self.minMoney floatValue] - allPrice > 0.0) {
                    [self.balanceButton setTitle:[NSString stringWithFormat:@"还差%.2f元", [self.minMoney floatValue] - allPrice] forState:UIControlStateNormal];
                    
                } else {
                    [self.balanceButton setTitle:@"去结算" forState:UIControlStateNormal];
                    self.balanceButton.backgroundColor = BVBaseOrangeColor;
                    self.balanceButton.enabled = YES;
                }
            }
            allShops += [BVShopCart shopCartCounts:detail];
        }
        
        // 商品总个数
        [self.shopCartFlag setTitle:[NSString stringWithFormat:@"%ld", (long)allShops] forState:UIControlStateNormal];
        
        // 已选商品总价格
        self.priceLabel.text = [NSString stringWithFormat:@"¥%.2f", allPrice];
        
        self.shopCartButton.enabled = YES;
        
        if (allShops == 0) { // 没有选择商品
            self.shopCartFlag.hidden = YES;
            self.priceLabel.text = @"¥0.00";
            self.balanceButton.enabled  = NO;
            self.shopCartButton.enabled = NO;
        }
        
    } else {
        self.shopCartFlag.hidden = YES;
        if (order != nil && [nowDate isEqualToString:orderDate]) {
            //            NSLog(@"有订单");
            self.priceLabel.text = @"¥0.00";
            self.balanceButton.enabled  = NO;
            self.shopCartButton.enabled = NO;
            [self.balanceButton setTitle:[NSString stringWithFormat:@"去结算"] forState:UIControlStateNormal];
        } else {
            //            NSLog(@"无订单");
            self.priceLabel.text = @"¥0.00";
            self.balanceButton.enabled  = NO;
            self.shopCartButton.enabled = NO;
            [self.balanceButton setTitle:[NSString stringWithFormat:@"还差%@元", self.minMoney] forState:UIControlStateNormal];
        }
    }
}

#pragma mark -- 获取当前时间
//获取当前时间
- (NSString *)getCurrentTime{
    NSDateFormatter *formatter = [NSDateFormatter new];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    return dateTime;
}

#pragma mark --  button 点击事件
/**
 *  查看我的购物车
 */
- (void)shopCartButtonClick {
    // 清空购物车
    // 清空数组
    [self.shopsCartCount removeAllObjects];
    
    // 商品数量
    [self.shopsCartCount addObjectsFromArray:[BVShopCart shopsCount:1]];
    
    // 设置tableview的尺寸
    self.shopCartTableView.x = 0;
    self.shopCartTableView.y = BVScreenH;
    self.shopCartTableView.width = BVScreenW;
    if (self.shopsCartCount.count < 8) {
        self.shopCartTableView.height = 44 * self.shopsCartCount.count;
    } else {
        self.shopCartTableView.height = 44 * 8;
    }
    
    // 设置蒙板尺寸蒙板
    self.coverButton.x = 0;
    self.coverButton.y = 0;
    self.coverButton.width  = BVScreenW;
    self.coverButton.height = BVScreenH - 40 - self.shopCartTableView.height;
    UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
    [window addSubview:_coverButton];

    NSTimeInterval duration = 0.3;
    [UIView animateWithDuration:duration animations:^{
        self.shopCartTableView.y = BVScreenH - 40 - self.shopCartTableView.height;
    }];
    
    // 刷新购物车tableview
    [self.shopCartTableView reloadData];
}
/**
 *  去结算
 */
- (void)correctOrderClick {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *dict = [defaults dictionaryForKey:@"USERINFO"];
    
    if (dict[@"id"]) {
        BVCorrectOrderViewController *correctOrderVC = [[BVCorrectOrderViewController alloc] init];
        correctOrderVC.delegate                      = self;
        ROOTNAVPUSH(correctOrderVC, YES);
        [self.coverButton removeFromSuperview];
    } else {
        BVLoginViewController * loginVC = [[BVLoginViewController alloc]init];

        ROOTNAVPUSH(loginVC, YES);
    }
}

/**
 *  添加商品
 */
- (void)addShops:(UIButton *)button {
    
    
    BVShopsLeftCategoryDetail *detailShops = self.shops[button.tag - 200];
    if ([BVShopCart lookUpShop:detailShops] != nil) { // 商品已在购物车
        // 修改商品
        [BVShopCart modifyShopToCartL:detailShops count:[BVShopCart shopCartCounts:detailShops] + 1];
    } else { // 新商品
        // 添加商品到数据库
        [BVShopCart addShopToCart:detailShops];
    }
    
    // 显示购物车标识
    self.shopCartFlag.hidden = NO;

    // 当前选中商品数量
    NSInteger selectedShops  = [self.shopCartFlag.currentTitle integerValue] + 1;

    // 显示商品数量
    [self.shopCartFlag setTitle:[NSString stringWithFormat:@"%ld", (long)selectedShops] forState:UIControlStateNormal];

    // 设置购物车基本信息
    [self setupBaseInfo];

    // 刷新tableview
    NSIndexPath *indexPath   = [NSIndexPath indexPathForRow:button.tag - 200 inSection:0];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];

    [[NSNotificationCenter defaultCenter] postNotificationName:ChangeShopCluntNotification object:nil userInfo:nil];
}

/**
 *  减少商品
 */
- (void)subShops:(UIButton *)button {
    
    BVShopsLeftCategoryDetail *detailShops = self.shops[button.tag - 500];

    // 当前选中商品数量
    NSInteger selectedShops = [BVShopCart shopCartCounts:detailShops] - 1;
    
    if (selectedShops > 0) {
        // 修改商品
        [BVShopCart modifyShopToCartL:detailShops count:selectedShops];
        
        // 显示商品数量
        [self.shopCartFlag setTitle:[NSString stringWithFormat:@"%ld", (long)selectedShops] forState:UIControlStateNormal];
    } else {
        // 从数据库删除数据
        [BVShopCart deleteShopFromCart:detailShops];
    }
    
    // 设置购物车基本信息
    [self setupBaseInfo];
    
    // 刷新tableview
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:button.tag - 500 inSection:0];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:ChangeShopCluntNotification object:nil userInfo:nil];
}

#pragma mark -- 设置导航栏
- (void)setupNav {
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStyleDone target:self action:@selector(backClick)];

    // 搜索框
    self.searchField = [[UITextField alloc] init];
    self.searchField.frame = CGRectMake(44, 35, BVScreenW - 44 * 2 - 10, 35);
    self.searchField.text = self.titleStr;
    self.searchField.placeholder = @" 请输入菜品名称";
    [self.searchField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    [self.searchField setValue:[UIFont boldSystemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
    self.searchField.backgroundColor = [UIColor clearColor];
    self.searchField.layer.cornerRadius = 4;
    self.searchField.layer.masksToBounds  = YES;
    self.searchField.layer.borderWidth = 0.5;
    self.searchField.layer.borderColor = [UIColor whiteColor].CGColor;
    self.searchField.textColor = [UIColor whiteColor];
    self.searchField.delegate = self;
    self.navigationItem.titleView = self.searchField;
    
    [self.searchField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}

#pragma mark -- 购物车tableview中商品的添加和减少
/**
 *  添加商品
 */
- (void)addBtnClick:(UIButton *)btn {
    BVShopsLeftCategoryDetail *shopDetail = self.shopsCartCount[btn.tag - 300];
    
    // 修改商品
    [BVShopCart modifyShopToCartL:shopDetail count:[BVShopCart shopCartCounts:shopDetail] + 1];
    
    // 当前选中商品数量
    NSInteger selectedShops = [self.shopCartFlag.currentTitle integerValue] + 1;
    
    // 显示商品数量
    [self.shopCartFlag setTitle:[NSString stringWithFormat:@"%ld", (long)selectedShops] forState:UIControlStateNormal];
    
    // 设置购物车基本信息
    [self setupBaseInfo];
    
    // 刷新tableview
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:btn.tag - 300 inSection:0];
    [self.shopCartTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    
    [self.tableView reloadData];
}

/**
 *  减少商品
 */
- (void)subBtnClick:(UIButton *)btn {
    BVShopsLeftCategoryDetail *shopDetail = self.shopsCartCount[btn.tag - 600];

    // 当前选中商品数量
    NSInteger selectedShops = [BVShopCart shopCartCounts:shopDetail] - 1;
    
    if (selectedShops > 0) {
        // 修改商品
        [BVShopCart modifyShopToCartL:shopDetail count:selectedShops];
        
        // 显示商品数量
        [self.shopCartFlag setTitle:[NSString stringWithFormat:@"%ld", (long)selectedShops] forState:UIControlStateNormal];
    } else {
        // 从数据库删除数据
        [BVShopCart deleteShopFromCart:shopDetail];
        
        // 从数组中删除
        [self.shopsCartCount removeObjectAtIndex:btn.tag - 600];
        
        // 设置tableview的尺寸
        if (self.shopsCartCount.count < 8) {
            self.shopCartTableView.height = 44 * self.shopsCartCount.count;
            self.shopCartTableView.y = BVScreenH - self.shopCartTableView.height - 40;
        } else {
            self.shopCartTableView.height = 44 * 8;
        }
        
        // 设置蒙板尺寸蒙板
        self.coverButton.x = 0;
        self.coverButton.y = 0;
        self.coverButton.width  = BVScreenW;
        self.coverButton.height = BVScreenH - 40 - self.shopCartTableView.height;
    }
    
    if (self.shopsCartCount.count == 0) { // 没有商品
        [self.coverButton removeFromSuperview];
    }
    
    // 设置购物车基本信息
    [self setupBaseInfo];
    
    // 刷新
    [self.shopCartTableView reloadData];
    
    [self.tableView reloadData];
}

/**
 *  移除遮盖
 */
- (void)removeCoverClick:(UIButton *)button {
    [button removeFromSuperview];
    NSTimeInterval duration = 0.3;
    [UIView animateWithDuration:duration animations:^{
        self.shopCartTableView.y = BVScreenH + 40 + self.shopCartTableView.height;
    }];
}

#pragma mark -- UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if ([self.delegate respondsToSelector:@selector(searchDetailShopsDidFinish:)]) {
        [self.delegate searchDetailShopsDidFinish:self];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark -- 返回
- (void)backClick {
    if ([self.delegate respondsToSelector:@selector(searchDetailShopsDidFinish:)]) {
        [self.delegate searchDetailShopsDidFinish:self];
        [self.navigationController popViewControllerAnimated:YES];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma makr -- BVCorrectOrderViewControllerDelegate
-(void)correctOrderViewControllerDidFinish:(BVCorrectOrderViewController *)correctOrder {
    if (self.shopCartTableView.y < BVScreenH) {
        // 设置蒙板尺寸蒙板
        self.coverButton.x = 0;
        self.coverButton.y = 0;
        self.coverButton.width  = BVScreenW;
        self.coverButton.height = BVScreenH - 40 - self.shopCartTableView.height;
        UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
        [window addSubview:_coverButton];
    }
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.searchField resignFirstResponder];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.searchField resignFirstResponder];
}

-(void)textFieldDidChange :(UITextField *)theTextField{
    NSLog( @"text changed: %@", theTextField.text);
    
    self.titleStr = theTextField.text;
    
    if (self.titleStr) {
        [self loadSearchData];
    }
}


@end
